package com.myccb.app.view.activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.myccb.app.AppStatus;
import com.myccb.app.R;
import com.myccb.app.base.RequestManager;
import com.myccb.app.base.BaseActivity;
import com.myccb.app.widget.*;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class FirstLoginActivity extends BaseActivity {
    private EditTextClearable et_phone;
    private EditTextClearable et_vcode;
    private EditTextClearable et_password;
    private TextView loginBtn;
    private TextView getVcodeBtn;

    private String phoneNum;
    private String vcode;
    private String password;
    private String userName;
    private String IDNum;
    private String mainBCNum;

    private boolean loginSuccess;

    LoadingCountdownDialog loadingCountdownDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firstlogin);
        initView();
    }
    private String phoneNumPattern = "^(\\+86)?((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\\d{8}$";
    private void initView(){
        (findViewById(R.id.open_account)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(FirstLoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });

        CommonToolBar commonToolBar=findViewById(R.id.common_toolbar);

        setSupportActionBar(commonToolBar.getToolbar());

        commonToolBar.setOnLeftButtonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            }
        });

        et_phone=findViewById(R.id.edittext_phone);

        et_vcode=findViewById(R.id.edittext_vcode);

        et_password=findViewById(R.id.edittext_password);

        loginBtn=findViewById(R.id.btn_login);

        getVcodeBtn=findViewById(R.id.get_vcode);

        et_vcode.setText("123456");
        et_vcode.setEnabled(false);
        getVcodeBtn.setEnabled(false);

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneNum=et_phone.getText().toString();
                password=et_password.getText().toString();
                new FirstLoginTask().execute();
            }
        });

        et_password.addOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus)
                    et_password.setText("");
            }
        });

        et_phone.addOnTextChangeListener(new LoginTextWatcher());
        et_vcode.addOnTextChangeListener(new LoginTextWatcher());
        et_password.addOnTextChangeListener(new LoginTextWatcher());

        loadingCountdownDialog=new LoadingCountdownDialog(this);
    }


    class LoginTextWatcher implements EditTextClearable.OnTextChangeListener{
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (et_password.getText()==null||et_vcode.getText()==null||et_phone.getText()==null){
                loginBtn.setEnabled(false);
                return;
            }
            if (!et_phone.getText().toString().matches(phoneNumPattern)){
                loginBtn.setEnabled(false);
                return;
            }
            if (et_vcode.getText().toString().length()<4){
                loginBtn.setEnabled(false);
                return;
            }
            if (et_password.getText().toString().length()<6){
                loginBtn.setEnabled(false);
                return;
            }
            loginBtn.setEnabled(true);
        }
    }

    class FirstLoginTask extends AsyncTask<Void, Void, Integer> {
        @Override
        protected void onPreExecute() {
            loadingCountdownDialog.show(30);
        }

        @Override
        protected Integer doInBackground(Void... voids) {
            int code=0;
            HashMap<String,String> postParams=new HashMap<>();
            postParams.put("action","firstLogin");
            //postParams.put("vcode",vcode);
            postParams.put("phoneNum",phoneNum);
            postParams.put("password",password);

            String result= RequestManager.getInstance(getApplicationContext()).requestSyn("login.php",RequestManager.TYPE_POST_FORM,postParams);


            Log.d("login",result);

            JSONObject jb = null;
            try {
                jb = new JSONObject(result);
                int status=jb.getInt("status");
                if(status==0){
                    loginSuccess=false;
                    code=jb.getInt("code");
                    //result=""+code;
                }
                else if (status==1){
                    loginSuccess=true;
                    jb=jb.getJSONObject("result");
                    userName=jb.getString("userName");
                    IDNum=jb.getString("IDNum");
                    mainBCNum=jb.getString("mainBCNum");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return code;
        }
        @Override
        protected void onPostExecute(Integer code) {
            loadingCountdownDialog.dismiss();
            if (loginSuccess){
                saveData();
                AppStatus.isLogin=true;

                SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Date curDate =  new Date(System.currentTimeMillis());
                AppStatus.lastLoginTime=formatter.format(curDate);

                finish();
            }
            else {
                showLoginError(code);
            }
        }
    }

    private void showLoginError(int code){



    }

    private void saveData() {
        SharedPreferences sp = getSharedPreferences("login_status", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("one_user_login_success", loginSuccess);
        if (loginSuccess) {
            String userInfo = userName + "," + phoneNum + "," + IDNum+","+mainBCNum;
            userInfo = Base64.encodeToString(userInfo.getBytes(), Base64.DEFAULT);
            editor.putString("user_info", userInfo);
        }
        editor.commit();
    }
}